package com.cwh.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cwh.entity.ActiveUser;
import com.cwh.entity.Baoxiaobill;
import com.cwh.service.BaoxiaobillService;
import com.cwh.service.WorkFlowService;
import com.cwh.utils.WorkFlowDirgamUtils;
import com.cwh.entity.Baoxiaobill;
@Controller
public class WorkFlowController {
	
	@Autowired
	private   WorkFlowService  workFlowService;
	
	@Autowired
	private  BaoxiaobillService  baoxiaobillService;
	
	//zip发布流程
	@RequestMapping("/deployProcess")
	public String deployProcess(MultipartFile  fileName,String processName) throws IOException {
	  workFlowService.saveNewDeploy(fileName.getInputStream(), processName);
	  //跳转add_process视图	
	  return "add_process";
	}
	
	//查看部署表act_re_deployment 与流程表信息act_re_procdef
	@RequestMapping("/processDefinitionList")
	public ModelAndView processDefinitionList() {
		ModelAndView mv = new ModelAndView();
		//查看部署表act_re_deployment
		List<Deployment> reDeploymentList = workFlowService.findReDeploymentList();
		//查看流程表信息act_re_procdef
		List<ProcessDefinition> reProcdefList = workFlowService.findReProcdefList();
		mv.addObject("depList", reDeploymentList);
		mv.addObject("pdList", reProcdefList);
		mv.setViewName("workflow_list");
		return mv;
	}
	
	//删除根据部署id删除部署流程 delDeployment?deploymentId=1
	@RequestMapping("/delDeployment")
	public String delDeployment(String deploymentId) {
		workFlowService.deleteDeploymentById(deploymentId);
		//跳转路径
		return "redirect:/processDefinitionList";
	}
	

	
	
	//报销申请
	//提交报销申请
	@RequestMapping("saveStartBaoxiao")
	public String saveStartBaoxiao(Baoxiaobill baoxiaobill) {
		//获取主体->获取账号
		ActiveUser activeUser =(ActiveUser) SecurityUtils.getSubject().getPrincipal();
		long userId=activeUser.getUserid();//用户id
		String username=activeUser.getUsername();//用户名
		//在报销表插入数据
		baoxiaobill.setCreatdate(new Date());//日期
		baoxiaobill.setState(1);//状态
		baoxiaobill.setUserId((int)userId);
		baoxiaobillService.inserBaoxiaobillReturnId(baoxiaobill);
		
		//获取插入baoxioabill后的id
		Integer baoxiaobillId = baoxiaobill.getId();
		//流图图的id
		String processKey=WorkFlowDirgamUtils.DIRGAM_ID;
		//启动流程
		workFlowService.saveStartProcess(processKey,baoxiaobillId,username);
		/*
		 受影响的表：
		Baoxiaobill
		act_hi_procinst 
		act_ru_execution 
​		act_ru_task
		act_hi_varinst
		 */
		//跳转到我的待办事务
		return "redirect:/myTaskList";
		
	}
	
	//办理任务start-------------------------------------------------------------------------------------------
	//显示数据
	@RequestMapping("/viewTaskForm")
	public ModelAndView saveStartBaoxiao1(String taskId) {
		//根据taskId获取报销(baoxiaobill)记录
		Baoxiaobill baoxiaoBill = workFlowService.findBaoxiaoBillByTaskId(taskId);
		//根据taskId获取历史审批(act_hi_comment)记录
		List<Comment> commentList = workFlowService.findCommentByTaskId(taskId);
		//根据taskId获取当前活动结点的线对象集合,前端渲染
		List<String> outcomeList = this.workFlowService.findOutComeListByTaskId(taskId);
		ModelAndView mv = new ModelAndView();
		mv.addObject("baoxiaoBill", baoxiaoBill);
		mv.addObject("commentList", commentList);
		mv.addObject("outcomeList", outcomeList);
		mv.addObject("taskId", taskId);
		mv.setViewName("approve_baoxiao");
		return mv;
		
	}
	/**
	 * 提交办理任务，提交表单
	 * @param id  报销表id
	 * @param taskId 进程id
	 * @param comment 批注信息
	 * @param outcome 选择的线
	 * @return
	 */
	@RequestMapping("/submitTask")
	public String submitTask(long id,String taskId,String comment,String outcome) {
		//获取主体->获取账号
		ActiveUser activeUser =(ActiveUser) SecurityUtils.getSubject().getPrincipal();
		String username = activeUser.getUsername();
		//办理任务
		workFlowService.submitTask(id,taskId,comment,outcome,username);
		System.out.println("选择的操作是："+outcome);
		
		return "redirect:/myTaskList";
	}
	
	//办理任务end----------------------------------------------------------------------------------------------
	
	//我的待办事务 根据用户名称查act_ru_task表 
	@RequestMapping("/myTaskList")
	public ModelAndView myTaskLis() {
		ModelAndView mv = new ModelAndView();
		ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
		String username = activeUser.getUsername();
		List<Task> taskList = workFlowService.findRuTaskListByUsername(username);
		mv.addObject("taskList", taskList);
		mv.setViewName("workflow_task");
		return mv;
		
	}
	
	//查看历史的批注信息
	@RequestMapping("/viewHisComment")
	public ModelAndView viewHisComment(long id) {
		//使用报销id,查询报销单记录
		Baoxiaobill baoxiaobill = baoxiaobillService.findBaoxiaobillById((int)id);
		//使用报销单id，查找历史批注信息
		List<Comment> commentList = workFlowService.findCommentByBaoxiaoBillId(id);
		ModelAndView mv = new ModelAndView();
		mv.addObject("baoxiaoBill", baoxiaobill);
		mv.addObject("commentList", commentList);
		mv.setViewName("workflow_commentlist");
		return mv;
		
	}
	
	//查看当前流程图
	@RequestMapping("/viewImage")
	public String viewImage(String deploymentId,String imageName,HttpServletResponse response) throws Exception {
		//获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
		InputStream in = workFlowService.findImageInputStream(deploymentId,imageName);
		//从response对象获取输出流程
		OutputStream out = response.getOutputStream();
		//将输入流中的数据读取出来，写到输出流中
		int b=-1;
		while((b=in.read())!=-1) {
			out.write(b);
		}
		//关闭流
		out.close();
		in.close();
		return null;
	}
	
	//查看流程定义图（查看当前活动节点，并使用红色的框标注）
	@RequestMapping("/viewCurrentImage")
	public ModelAndView viewCurrentImage(String taskId) {
		//通过taskId查询act_re_procdef记录
		ProcessDefinition pd = workFlowService.findProcessDefinitionByTaskId(taskId);
		//查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中
		Map<String, Object> map = workFlowService.findCoordingByTask(taskId);
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("deploymentId", pd.getDeploymentId());
		mv.addObject("imageName", pd.getDiagramResourceName());
		mv.addObject("acs", map);
		mv.setViewName("viewimage");
		return mv;
	}
	
	//我的待办事务->查看当前流程图
	@RequestMapping("/viewCurrentImageByBill")
	public String viewCurrentImageByBill(long billId,ModelMap model) {
		String BUSSINESS_KEY = WorkFlowDirgamUtils.DIRGAM_ID + "." + billId;
		//通过bussinessKey查找act_ru_task表
		Task task = this.workFlowService.findTaskByBussinessKey(BUSSINESS_KEY);
		/**一：查看流程图*/
		//通过taskId查询act_re_procdef记录
		ProcessDefinition pd = workFlowService.findProcessDefinitionByTaskId(task.getId());

		model.addAttribute("deploymentId", pd.getDeploymentId());
		model.addAttribute("imageName", pd.getDiagramResourceName());
		/**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
		Map<String, Object> map = workFlowService.findCoordingByTask(task.getId());

		model.addAttribute("acs", map);
		return "viewimage";
	}
}
